package xyz.linyuxb.utils;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.util.Properties;

/**
 * @Author: linyuxb
 * @Date: 2021/11/14 11:17 上午
 * @Desc:
 */
public abstract class QuartzScript implements BaseScript, Job {
    private static final String JOB_KEY_NAME = "%s.job-key.name";
    private static final String JOB_KEY_GROUP = "%s.job-key.group";
    private static final String TRIGGER_KEY_NAME = "%s.trigger-key.name";
    private static final String TRIGGER_KEY_GROUP = "%s.trigger-key.group";
    private static final String CRON_SCHEDULE = "%s.cron-schedule";

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        MyJobDetailImpl jobDetail = (MyJobDetailImpl) jobExecutionContext.getJobDetail();
        this.doScript(jobDetail.getProperties());
    }

    @Override
    public void doScript(Properties properties) {

    }

    /**
     * 获取项目描述
     *
     * @return
     */
    public abstract String getJokDesc();

    /**
     * 创建作业任务调度器
     *
     * @return
     * @throws SchedulerException
     */
    public Scheduler createScheduler() throws SchedulerException {
        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        return schedulerFactory.getScheduler();
    }

    /**
     * 创建⼀个作业任务
     *
     * @param jobClass
     * @return
     */
    public MyJobDetailImpl createJob(Class<? extends QuartzScript> jobClass,
                                     String jodDesc, Properties load) {
        String jobName = load.getProperty(String.format(JOB_KEY_NAME, jodDesc));
        String myJob = load.getProperty(String.format(JOB_KEY_GROUP, jodDesc));
        MyJobBuilder jobBuilder = MyJobBuilder.newJob(jobClass);
        jobBuilder.withIdentity(jobName, myJob);
        return jobBuilder.build();
    }

    /**
     * 创建作业任务时间触发器
     * cron表达式由七个位置组成，空格分隔
     * 1、Seconds（秒） 0~59
     * 2、Minutes（分） 0~59
     * 3、Hours（⼩时） 0~23
     * 4、Day of Month（天）1~31,注意有的⽉份不⾜31天
     * 5、Month（⽉） 0~11,或者
     * JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC
     * 6、Day of Week(周) 1~7,1=SUN或者 SUN,MON,TUE,WEB,THU,FRI,SAT
     * 定义⼀个job，需实现Job接⼝
     * 7、Year（年）1970~2099 可选项
     * 示例：
     * 0 0 11 * * ? 每天的11点触发执⾏⼀次
     * 0 30 10 1 * ? 每⽉1号上午10点半触发执⾏⼀次
     */
    public Trigger createTrigger(String jodDesc, Properties load) {
        String triggerName = load.getProperty(String.format(TRIGGER_KEY_NAME, jodDesc));
        String myTrigger = load.getProperty(String.format(TRIGGER_KEY_GROUP, jodDesc));
        String cronSchedule = load.getProperty(String.format(CRON_SCHEDULE, jodDesc));
        // 创建时间触发器，按⽇历调度
        return TriggerBuilder.newTrigger()
                .withIdentity(triggerName, myTrigger)
                .startNow()
                .withSchedule(CronScheduleBuilder.cronSchedule(cronSchedule))
                .build();
    }
}
